package com.hjs.servlet.Other;

import com.hjs.bean.DamageCategory;
import com.hjs.bean.DamageType;
import com.hjs.bean.DamageTypeInfo;
import com.hjs.bean.PavementType;
import com.hjs.mapper.DamageTypeMapper;
import com.hjs.tools.Mapper;
import com.hjs.tools.RequestUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@WebServlet("/getAllDamageType")
public class GetDamageType extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        RequestUtil requestUtil = new RequestUtil(request, response);
        Mapper<DamageTypeMapper> damageTypeMapperMapper = new Mapper<>(DamageTypeMapper.class);
        try {
            DamageTypeMapper mapper = damageTypeMapperMapper.getMapper();
            if (requestUtil.getString("pavementTypeId") != null) {
                List<DamageCategory> damageCategories = mapper.getAllDamageCategoryByPavementTypeId(
                        requestUtil.getInt("pavementTypeId"));
                requestUtil.responseWrite(Mapper.toJsonString(damageCategories));
            } else if (requestUtil.getString("damageCategoryId") != null) {
                List<DamageType> damageTypes = mapper.getAllDamageTypeByCategoryId(
                        requestUtil.getInt("damageCategoryId"));
                ArrayList<DamageTypeInfo> damageTypeInfos = new ArrayList<>();
                damageTypes.forEach(damageType -> damageTypeInfos.add(new DamageTypeInfo(damageType)));
                requestUtil.responseWrite(Mapper.toJsonString(damageTypeInfos));
            } else {
                List<PavementType> allPavementType = mapper.getAllPavementType();
                requestUtil.responseWrite(Mapper.toJsonString(allPavementType));
            }
        } catch (Exception e) {
            log.error(e.toString());
            requestUtil.responseFail("未知错误");
        } finally {
            damageTypeMapperMapper.closeSession();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    }
}
